package com.networklib.task.base;

import com.networklib.TaskResult;
import com.networklib.ThreadPoolUtil;

import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * Created by ASUS on 2017/6/14.
 */

public abstract class TaskService implements ITaskService, ATask.TaskListener {
    private TaskCallBack taskCallBack;
    protected LinkedHashMap<String, ATask> aTaskHashMap = new LinkedHashMap<>();
    private ThreadPoolUtil threadPoolUtil = ThreadPoolUtil.getInstance();

    public TaskService addTask(ATask aTask) {
        aTask.setTaskListener(this);
        aTaskHashMap.put(aTask.getTag(), aTask);
        return this;
    }

    @Override
    public final void submit(ATask aTask) {
        threadPoolUtil.excute(aTask);
    }

    @Override
    public boolean before(TaskResult taskResult) {
        return taskCallBack != null && taskCallBack.before(taskResult);
    }

    @Override
    public void onComplete(TaskResult taskResult) {
        if (taskCallBack != null) {
            taskCallBack.onComplete(taskResult);
        }
    }

    @Override
    public void after(TaskResult taskResult) {
        if (taskCallBack != null) {
            taskCallBack.after(taskResult);
        }
    }

    public void setTaskCallBack(TaskCallBack taskCallBack) {
        this.taskCallBack = taskCallBack;
    }

    public interface TaskCallBack {
        boolean before(TaskResult taskResult);

        void onComplete(TaskResult taskResult);

        void after(TaskResult taskResult);
    }
}
